<template>
  <div>
    <el-card class="box-card box-card-p10 box-card-pd0">
      <el-form
        class="search-form"
        ref="searchForm"
        :model="searchForm"
        label-width="50px"
      >
        <el-form-item label="分组" prop="grouping">
          <el-select
            :disabled="userGroup.role != 'Administrator' && !userGroup.isLeader"
            v-model="searchForm.grouping"
            @change="changeGroup"
            placeholder="请选择"
            filterable
            size="small"
          >
            <el-option
              v-for="item in searchForm.groupingOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班别" prop="class">
          <el-select
            v-model="searchForm.class"
            placeholder="请选择"
            filterable
            clearable
            multiple
            size="small"
          >
            <el-option
              v-for="item in searchForm.classOptions"
              :key="item.id"
              :label="item.shiftName"
              :value="item.shiftName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input
            placeholder="请输入人员姓名"
            v-model="searchForm.userName"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label-width="10px">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="onSearch"
          >查询</el-button
          >
          <el-button
            v-if="userGroup.role == 'Administrator' || userGroup.isLeader"
            size="small"
            @click="resetForm('searchForm')"
          >重置</el-button
          >
          <el-button
            size="small"
            type="warning"
            icon="el-icon-download"
            @click="exportExcel"
          >导出</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card box-card-p15">
      <div class="box-btn">
        <div class="box-btn-l">
          <span class="ft_20">{{showDateTitle}} 检查医生排班表</span>
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content" class="tableTrips" v-html="tips"></div>
            <el-button style="color:#666; border:none;padding:0 5px">
              班别说明
              <i class="el-icon-info el-icon--right"></i>
            </el-button>
          </el-tooltip>
          <!-- <el-select
            v-model="dateValue"
            placeholder="请选择"
            size="mini"
            style="width:auto"
            @change="changeDate"
          >
            <el-option
              v-for="item in dateOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>-->
        </div>
        <div class="box-btn-r">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-arrow-left"
              @click="prevDate"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-arrow-right"
              @click="nextDate"
            ></el-button>
          </el-button-group>
          <el-button type="primary" size="small" @click="clickCurrentDate">
            {{dateLabel}}
          </el-button>
        </div>
      </div>
      <el-table
        :data="listData"
        v-loading="dataLoading"
        :show-header="false"
        border
        :cell-class-name="headerClass"
        :header-cell-style="tableStyle.headerCellStyle"
        style="width: 100%"
        class="hover-class"
        id="exportExcelData"
      >
        <el-table-column
          min-width="80"
          prop="userName"
          label="星期"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.row.support
              ? "支援(" + scope.row.userName + ")"
              : scope.row.userName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in listDataMonths"
          :key="index"
          align="center"
        >
          <template slot-scope="scope">
            <el-tooltip
              placement="bottom"
              :disabled="!scope.row.items[index].date"
            >
              <div slot="content">
                <div
                  v-for="ditem in scope.row.items[index].tips"
                  :key="ditem.shiftName"
                >
                  {{ditem.shiftName +
                    "：" +
                    ditem.startTime +
                    "~" +
                    ditem.endTime +
                    (ditem.isNextDay ? "(次日)" : "")}}
                </div>
              </div>
              <span class v-html="scope.row.items[index].shiftName"></span>
            </el-tooltip>
            <!-- {{ scope.row.items[index].shiftName }} -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import {
  getQueryshifts,
  getGroupList,
  getQueryGroupDuties
} from '@/api/api-rostering.js'
import store from '@/store'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import tableStyle from '@/utils/tableStyle.js'
export default {
  data() {
    return {
      userGroup: {},
      groupId: '',
      searchForm: {
        grouping: '',
        groupingOptions: [],
        class: [],
        classOptions: [],
        userName: ''
      },
      dateValue: '周排班',
      dateOptions: ['周排班', '月排班'],
      dateLabel: '本周',
      dateNum: 0,
      nowMonth: '',
      nowYear: '',
      startDay: '',
      endDay: '',
      dataLoading: false,
      tableStyle: tableStyle,
      listData: [],
      listDataWeeks: [],
      listDataWeeksArr: [],
      listDataMonths: [],
      listDataMonthsArr: [],
      tips: '',
      showDateTitle: ''
    }
  },
  mounted() {
    this.userGroup = store.getters.userInfo
    this.getInitDate()
    this.getGroupingOptions()
  },
  methods: {
    getInitDate() {
      this.startDay = this.getDate(0)
      this.endDay = this.getDate(-6)
    },
    // 获取分组下拉数据
    getGroupingOptions() {
      this.searchForm.grouping = ''
      getGroupList().then(res => {
        if (!res) return
        this.searchForm.groupingOptions = res.result
        if (this.userGroup.groupId) {
          this.searchForm.grouping = this.userGroup.groupName
          this.groupId = this.userGroup.groupId
        } else {
          this.searchForm.grouping = this.searchForm.groupingOptions[0].name
          this.groupId = this.searchForm.groupingOptions[0].id
        }
        this.getClassOptions()
        this.getListData()
      })
    },
    changeGroup() {
      let i = this.searchForm.groupingOptions.findIndex(
        gitem => gitem.name == this.searchForm.grouping
      )
      this.groupId = this.searchForm.groupingOptions[i].id
      this.getClassOptions()
    },
    // 获取班别下拉数据
    getClassOptions() {
      this.tips = ''
      getQueryshifts({ groupId: this.groupId }).then(res => {
        if (!res) return
        this.searchForm.classOptions = res.result
        if (res.result.length > 0) {
          for (let i = 0; i < res.result.length; i++) {
            this.tips +=
              '<div>' +
              res.result[i].shiftName +
              '：' +
              res.result[i].startTime +
              '~' +
              res.result[i].endTime +
              (res.result[i].isNextDay ? '(次日)' : '') +
              '</div>'
          }
        } else {
          this.tips = '无'
        }
      })
    },
    // 搜索
    onSearch() {
      this.getListData()
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 导出
    exportExcel() {
      var wb = XLSX.utils.table_to_book(
        document.getElementById('exportExcelData')
      )
      let wscols = [
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 },
        { wch: 10 }
      ]
      wb.Sheets.Sheet1['!cols'] = wscols
      // 得到二进制字符串作为输出
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'binary'
      })
      FileSaver.saveAs(
        new Blob([this.s2ab(wbout)], {
          type: 'application/octet-stream'
        }),
        this.$route.meta.title + this.getDate(0) + '.xlsx'
      )
    },
    s2ab: function (s) {
      var cuf
      var i
      if (typeof ArrayBuffer !== 'undefined') {
        cuf = new ArrayBuffer(s.length)
        var view = new Uint8Array(cuf)
        for (i = 0; i !== s.length; i++) {
          view[i] = s.charCodeAt(i) & 0xff
        }
        return cuf
      } else {
        cuf = new Array(s.length)
        for (i = 0; i !== s.length; ++i) {
          cuf[i] = s.charCodeAt(i) & 0xff
        }
        return cuf
      }
    },
    // 排班类型
    changeDate(e) {
      this.dateLabel = e === '周排班' ? '本周' : '本月'
    },
    // 获取时间
    getDate(n) {
      const now = new Date()
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      let date = now.getDate()
      let day = now.getDay()
      if (day !== 0) {
        n = n + (day - 1)
      } else {
        n = n + day
      }
      if (day) {
        if (month > 1) {
          // month = month
        } else {
          year = year - 1
          month = 12
        }
      }
      now.setDate(now.getDate() - n)
      year = now.getFullYear()
      month = now.getMonth() + 1
      date = now.getDate()
      const s =
        year +
        '/' +
        (month < 10 ? '0' + month : month) +
        '/' +
        (date < 10 ? '0' + date : date)
      let getWeekDate = this.getMonthWeek(year, month, date)
      this.showDateTitle =
        getWeekDate.getYear +
        '年 ' +
        getWeekDate.getMonth +
        '月 第' +
        getWeekDate.getWeek +
        '周'
      return s
    },
    // 得到本月的第几周
    getMonthWeek(a, b, c) {
      console.log('aaa', a, b, c)
      /**
       * a = d = 当前日期
       * b = 6 - w = 当前周的还有几天过完(不算今天)
       * a + b 的和在除以7 就是当天是当前月份的第几周
       */
      var date = new Date(a, parseInt(b) - 1, parseInt(c))
      var w = date.getDay()
      var d = date.getDate()
      if (w == 0) {
        w = 7
      }
      // debugger
      var config = {
        getMonth: date.getMonth() + 1,
        getYear: date.getFullYear(),
        getWeek: Math.ceil((d + 6 - w) / 7)
      }
      // console.log('v', config)
      return config
    },
    // 日期转星期
    getWeek(dateString) {
      var dateArray = dateString.split('/')
      var date = new Date(
        dateArray[0],
        parseInt(dateArray[1] - 1),
        dateArray[2]
      )
      return '星期' + '日一二三四五六'.charAt(date.getDay())
    },
    // 获取上一周
    prevDate() {
      this.dateNum += 7
      this.startDay = this.getDate(this.dateNum)
      this.endDay = this.getDate(this.dateNum - 6)
      this.getListData()
    },
    // 获取下一周
    nextDate() {
      this.dateNum -= 7
      this.startDay = this.getDate(this.dateNum)
      this.endDay = this.getDate(this.dateNum - 6)
      this.getListData()
    },
    // 获取当前时间
    clickCurrentDate() {
      this.getInitDate()
      this.getListData()
    },
    // 获取排班统计
    getListData() {
      this.dataLoading = true
      // 获取分组id
      let groupIds = []
      // let groups = this.searchForm.groupingOptions;
      // if (groups.length > 0) {
      //   for (let i = 0; i < groups.length; i++) {
      //     for (let j = 0; j < this.searchForm.grouping.length; j++) {
      //       if (groups[i].name == this.searchForm.grouping[j]) {
      //         groupIds.push(groups[i].id);
      //       }
      //     }
      //   }
      // }
      groupIds.push(this.groupId)
      // 获取班别id
      let shiftIds = []
      let classs = this.searchForm.classOptions
      if (classs.length > 0) {
        for (let i = 0; i < classs.length; i++) {
          for (let j = 0; j < this.searchForm.class.length; j++) {
            if (classs[i].shiftName == this.searchForm.class[j]) {
              shiftIds.push(classs[i].id)
            }
          }
        }
      }
      let data = {
        groupIds: groupIds,
        userName: this.searchForm.userName,
        shiftIds: shiftIds,
        startDay: this.startDay,
        endDay: this.endDay
      }
      getQueryGroupDuties(data).then(res => {
        if (!res) return
        const result = []
        res.result.forEach((item, index) => {
          result.push({
            userName: item.userName,
            items: [],
            support: item.support
          })
          item.items.forEach(item2 => {
            let nstr = []
            for (let ss of item2.detail) {
              nstr.push(
                '<span style="color:' +
                  ss.color +
                  '">' +
                  ss.shiftName +
                  '</span>'
              )
            }
            result[index].items.push({
              shiftName: nstr.join('<span>+</span>'),
              tips: item2.detail,
              date: item2.date,
              week: this.getWeek(item2.date)
            })
          })
        })
        if (result.length > 0) {
          this.listDataWeeks = []
          this.listDataMonths = []
          this.listDataWeeksArr = []
          this.listDataMonthsArr = []
          result[0].items.forEach(item => {
            this.listDataMonths.push({
              shiftName: item.date
            })
            this.listDataWeeks.push({
              shiftName: item.week
            })
          })
          this.listDataMonthsArr.push({
            userName: '日期',
            items: this.listDataMonths
          })
          this.listDataWeeksArr.push({
            userName: '星期',
            items: this.listDataWeeks
          })
          this.listData = this.listDataWeeksArr
            .concat(this.listDataMonthsArr)
            .concat(result)
        } else {
          this.listData = this.listDataWeeksArr.concat(this.listDataMonthsArr)
        }
        this.dataLoading = false
      })
    },
    // 修改第一条样式
    headerClass(row) {
      if (row.rowIndex === 0) {
        return 'header-class'
      } else if (row.rowIndex === 1) {
        return 'td-class'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.box-card {
  margin: 10px;
  .search-form {
    overflow: hidden;
    .el-form-item {
      width: 25%;
      float: left;
      .el-select {
        width: 100%;
      }
    }
  }
}
.box-btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.ft_20{
  font-size: 20px;
}
</style>
<style>
.header-class {
  background: #00c0ef;
  color: #fff;
}
.hover-class .el-table__body tr:hover td.header-class {
  background: #00c0ef !important;
  color: #fff !important;
}
.hover-class .el-table__body td.header-class,
.hover-class .el-table__body td.td-class {
  border-right: none;
  font-weight: 600;
}
.hover-class .el-table__body td.td-class {
  color: #333;
}
</style>
